import 'package:flutter/material.dart';
import '../../../../models/user_list_model.dart';
import '../../../../services/messageUtil.dart';
import '../../../../services/httpsClient.dart';
import 'package:get/get.dart';

class ProjectUserController extends GetxController {
  //TODO: Implement ProjectUserController
  bool isLoading = true; //请求防抖控制
  HttpsClient httpsClient = HttpsClient();
  
  RxInt projectId = 0.obs; //当前项目id
  //新增用户名称
  RxString createUserName = ''.obs;
  //新增用户电话
  RxString createUserPhone = ''.obs;
  //新增用户登录密码
  RxString createUserPassword = ''.obs;

  //用户数据
  RxList<UserItemModelData?> userList = <UserItemModelData?>[].obs;
  //用户总数
  RxInt totalUser = 0.obs;
  //当前页码
  RxInt currentPage = 1.obs;
  //总页数
  RxInt totalPages = 1.obs;
  //每页数量
  RxInt pageSize = 10.obs;
  @override
  void onInit() {
    super.onInit();
  }

  @override
  void onReady() {
    super.onReady();
  }

  @override
  void onClose() {
    super.onClose();
  }
  
  //设置当前项目id
  void setProjectId(int id) {
    projectId.value = id;
    getUserListData();
    update();
  }

  // 切换页码
  void changePage(int page) {
    if (page >= 1 && page <= totalPages.value) {
      currentPage.value = page;
      getUserListData();
      update();
    }
  }
  
  //获取接口列表
  getUserListData() async {
    var response = await httpsClient.get(
      "v1/user/list",
      params: {
        'project_id': projectId.value,
        'page': currentPage.value,
        'page_size': pageSize.value,
      },
    );
    if (response != null) {
      var group = UserListModel.fromJson(response.data);
      if (group.data?.items != null && group.data!.items!.isNotEmpty) {
        userList.value = group.data!.items ?? [];
      } else {
        userList.value = [];
      }
      totalPages.value = ((group.data?.total ?? 0).toInt() /(group.data?.limit ?? pageSize.value)).ceil();
      totalUser.value = group.data?.total ?? 0;
      update();
    }
  }
  
  // 提交新增分组表单
  void submitCreateUserForm() async {
    if (isLoading) {
      isLoading = false;

      var response = await httpsClient.post(
        "v1/user/create",
        data: {
          "name": createUserName.value,
          "phone": createUserPhone.value,
          "password": createUserPassword.value,
        },
      );

      if (response != null) {
        if (response.data['code'] == 0) {
          MessageUtil.showSuccess(
            message: "添加成功",
            config: MessageUtilConfig(
              duration: const Duration(seconds: 1),
              indicatorColor: Colors.green,
            ),
          );
          createUserName.value = '';
          createUserPhone.value = '';
          createUserPassword.value = '';
          // 关闭对话框
          Get.back();
        } else {
          MessageUtil.showError(message: response.data["message"]);
        }
      } else {
        MessageUtil.showError(message: "网络异常");
      }
      isLoading = true;
    }
  }

}
